package com.yonyou.distribute.service;

import com.yonyou.distribute.zk.ZKClient_2;
import com.yonyou.distribute.zk.ZKDistributedLock_2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * p66 p67
 * zk实现分布式锁
 *
 * 解决阻塞
 */
@Slf4j
@Service
public class ZkService_2 {

    @Autowired
    private ZKClient_2 zkClient_2;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Transactional
    public void deduct() {

        ZKDistributedLock_2 lock = zkClient_2.getLock("lock");
        lock.lock();
        try{
            // 1、查询库存
            String stock = this.stringRedisTemplate.opsForValue().get("stock");
            // 2、判断库存是否充足
            if(!StringUtils.isEmpty(stock)){
                Integer st = Integer.valueOf(stock);
                if(st > 0){
                    //3、更新库存到数据库
                    this.stringRedisTemplate.opsForValue().set("stock", String.valueOf(--st));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
